package com.xingshi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.xingshi.springbootinit.constant.BiMqConstant;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于创建交换机和队列（仅需启动一次）
 */
public class BiMqInit {
    public static void main(String[] args) {
        try{
            //创建频道
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setUsername("soda");
            factory.setPassword("soda");
            factory.setVirtualHost("/bi");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            //声明死信交换机
            channel.exchangeDeclare(BiMqConstant.BI_DL_EXCHANGE_NAME,BiMqConstant.BI_DIRECT_EXCHANGE,true);
            //声明死信队列
            channel.queueDeclare(BiMqConstant.BI_DL_QUEUE_NAME,true,false,false,null);
            //绑定交换机与队列
            channel.queueBind(BiMqConstant.BI_DL_QUEUE_NAME,BiMqConstant.BI_DL_EXCHANGE_NAME,BiMqConstant.BI_DL_ROUTING_KEY);

            //声明参数
            Map<String, Object> argumentsMap = new HashMap<>();
            argumentsMap.put("x-dead-letter-exchange",BiMqConstant.BI_DL_EXCHANGE_NAME);
            argumentsMap.put("x-dead-letter-routing-key",BiMqConstant.BI_DL_ROUTING_KEY);

            //声明交换机
            channel.exchangeDeclare(BiMqConstant.BI_EXCHANGE_NAME,BiMqConstant.BI_DIRECT_EXCHANGE,true);
            //声明队列
            channel.queueDeclare(BiMqConstant.BI_QUEUE_NAME,true,false,false,argumentsMap);
            //绑定交换机与队列
            channel.queueBind(BiMqConstant.BI_QUEUE_NAME,BiMqConstant.BI_EXCHANGE_NAME,BiMqConstant.BI_ROUTING_KEY);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
